package cn.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingCluster;
import org.apache.curator.test.TestingServer;
import org.apache.curator.test.TestingZooKeeperServer;

import java.io.File;

/**
 * ClassName: TestFirst
 * Desc:  测试Curator-Test（TestingServer）
 * Date： 2016/12/7
 * Created：shaom
 */
public class TestFirst {

    static String test_path = "/curator_test_path";
    public static final String connectString = "master:2181,slave01:2181,slave02:2181";

    /**
     * 测试模拟服务端
     *
     * @throws Exception
     */
    void testingServer() throws Exception {
        // 服务端。自定义端口和dataDir
        // 不指定dataDir 那么默认在系统的临时目录中创建临时目录java.io.tmpdir
        TestingServer server = new TestingServer(2181, new File("d://var/zk"));

        // 客户端
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(5000, 3))
                .build();
        client.start();


        client.create().creatingParentsIfNeeded().forPath(test_path + "/c1");
        client.create().creatingParentsIfNeeded().forPath(test_path + "/c2");

        //
        System.out.println(client.getChildren().forPath(test_path));
        server.close();
    }

    /**
     * 模拟服务端集群
     */
    void testCluster() throws Exception {

        TestingCluster cluster = new TestingCluster(3);
        cluster.start();
        Thread.sleep(2000);

        TestingZooKeeperServer leader = null;

        for (TestingZooKeeperServer zooKeeperServer : cluster.getServers()) {

            System.out.print(zooKeeperServer.getInstanceSpec().getServerId() + "-");
            System.out.print(zooKeeperServer.getQuorumPeer().getServerState() + "-");
            System.out.println(zooKeeperServer.getInstanceSpec().getDataDirectory().getAbsolutePath());

            if (zooKeeperServer.getQuorumPeer().getServerState().equals("leading")) {
                leader = zooKeeperServer;
            }
        }

        leader.kill();

        System.out.println("After leader kill： ");
        for (TestingZooKeeperServer keeperServer : cluster.getServers()) {
            System.out.print(keeperServer.getInstanceSpec().getServerId() + "-");
            System.out.print(keeperServer.getQuorumPeer().getServerState() + "-");
            System.out.println(keeperServer.getInstanceSpec().getDataDirectory().getAbsolutePath());
        }
        cluster.stop();

    }


}
